package com.leetcode;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;

/**
 * 429. N 叉树的层序遍历
 *
 * @author fy
 * @date 2022/4/8 17:29
 */
public class Solution429 {

    static class Node {
        public int val;
        public List<Node> children;

        public Node() {
        }

        public Node(int _val) {
            val = _val;
        }

        public Node(int _val, List<Node> _children) {
            val = _val;
            children = _children;
        }
    }

    public List<List<Integer>> levelOrder(Node root) {
        List<List<Integer>> res = new ArrayList<>();
        if (root == null) {
            return res;
        }

        Queue<Node> queue = new ArrayDeque<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            List<Integer> list = new ArrayList<>();
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                Node node = queue.poll();
                list.add(node.val);
                if (node.children != null && !node.children.isEmpty()) {
                    for (Node child : node.children) {
                        queue.offer(child);
                    }
                }
            }
            res.add(list);
        }
        return res;
    }

    public static void main(String[] args) {
        Node child31 = new Node(5, null);
        Node child32 = new Node(6, null);
        List<Node> l3 = new ArrayList<>();
        l3.add(child31);
        l3.add(child32);

        Node child21 = new Node(3, l3);
        Node child22 = new Node(2, null);
        Node child23 = new Node(4, null);
        List<Node> l2 = new ArrayList<>();
        l2.add(child21);
        l2.add(child22);
        l2.add(child23);

        Node root = new Node(1, l2);

        List<List<Integer>> res = new Solution429().levelOrder(root);
        System.out.println(res);
    }

}
